
import discord
from discord.ext import commands

from urllib.request import urlopen, Request
import configparser 
import os

from utils import printProgressBar

try:
    from config import *
except:
    TOKEN = None
    CHANNELS = None

intents = discord.Intents(guilds=True, members=True, bans=True,
                          emojis=True, integrations=True, invites=True,
                          voice_states=True, presences=True, messages=True,
                          guild_messages=True, dm_messages=True, reactions=True,
                          guild_reactions=True, dm_reactions=True, typing=True,
                          guild_typing=True, dm_typing=True, message_content=True)


client = commands.Bot(
    command_prefix="!",
    intents=intents,
    debug_guilds=[682240305235624014]
)

os.makedirs("attachments", exist_ok=True)

async def load_emojies(client: commands.Bot) -> None:
    guild = client.get_guild(GUILD_ID)
    if guild is None: return
    print(f"Loading {guild.name}'s emojies...")

    dirname = f"attachments/${guild.name}.{GUILD_ID}/"
    os.makedirs(dirname, exist_ok=True)

    for emoji in guild.emojis:
        print(f"    {emoji.name}...")
        req = Request(emoji.url, headers={'User-Agent': 'Mozilla/5.0'})
        fl = urlopen(req).read()
        
        name = emoji.name
        name = dirname+name + ".png"

        with open(name, "+wb") as file: file.write(fl)

async def add_message_to_ini(messages_ini, message, index, attachments):
    messages_ini.add_section(f"Message {index}")
    messages_ini.set(f"Message {index}", "author", f"{message.author}")
    messages_ini.set(f"Message {index}", "text", message.content.replace('%', '%%'))
    messages_ini.set(f"Message {index}", "attachments", ' '.join(attachments))

async def load(client):
    for channel_id in CHANNELS:
        channel = client.get_channel(channel_id)
      
        index = 0
        messages_count = 0
        messages = channel.history(limit=None, oldest_first=True)

        printProgressBar(0, 1, prefix=f'Getting count of messages (#{channel.name})', length=50)
        async for message in messages: messages_count += 1
        printProgressBar(1, 1, prefix=f'Getting count of messages (#{channel.name})', suffix='Complete', length=50)

        dirname = f"attachments/#{channel.name}.{channel_id}/"
        os.makedirs(dirname, exist_ok=True)

        messagecfg = configparser.ConfigParser()
        textfile = open(dirname+"messages.ini", "w+")

        messages = channel.history(limit=None, oldest_first=True)
        printProgressBar(0, messages_count, prefix=f'Download messages: #{channel.name}', length=50)
        async for message in messages:
            items_list = list()
            printProgressBar(index, messages_count, prefix=f'Download messages: #{channel.name}', length=50)

            for attach in message.attachments:
                req = Request(attach.url, headers={'User-Agent': 'Mozilla/5.0'})
                fl = urlopen(req).read()
                
                name = attach.filename
                if attach.filename == "unknown.png": name = str(index)+name

                name = dirname+name

                items_list.append(name)

                with open(name, "+wb") as file: file.write(fl)
           
            await add_message_to_ini(messagecfg, message, index, items_list)
            index += 1

        printProgressBar(index, messages_count, prefix=f'Download messages: #{channel.name}', suffix='Complete', length=50)

        messagecfg.write(textfile)
        textfile.close()

    return exit(0)


@client.event
async def on_ready() -> None:
    await load_emojies(client)
    await load(client)

if TOKEN in [None, ""]: TOKEN=input("Please, write your discord bot token: ")
if CHANNELS in [None, []]: 
    CHANNELS=[int(cid) for cid in input("Please, write your discord channels_id's with comma (,): ").split(",")]

client.run(TOKEN)


